/**
 * 国际化(l10n)管理模块
 * 支持多语言切换、缓存、加载状态管理
 */
class I18nManager {
    constructor() {
        // 配置项
        this.config = {
            supportedLanguages: ['zh-CN', 'en', 'ru'],
            defaultLanguage: 'zh-CN',
            cookieName: 'preferred_language',
            cookieExpires: 365,
            localePath: '/locales/'
        };
        
        // 状态
        this.currentLanguage = this.config.defaultLanguage;
        this.translations = {};
        this.isLoading = false;
        
        // DOM元素
        this.languageButtons = document.querySelectorAll('.language-switcher button');
        this.dynamicContentElements = document.querySelectorAll('[data-i18n]');
    }
    
    /**
     * 初始化国际化模块
     */
    init() {
        // 检测首选语言
        this.detectPreferredLanguage();
        
        // 绑定事件
        this.bindEvents();
        
        // 加载语言文件
        this.loadLanguage(this.currentLanguage);
    }
    
    /**
     * 检测用户首选语言
     */
    detectPreferredLanguage() {
        // 1. 从本地存储获取
        const savedLanguage = localStorage.getItem(this.config.cookieName);
        if (this.isValidLanguage(savedLanguage)) {
            this.currentLanguage = savedLanguage;
            return;
        }
        
        // 2. 从Cookie获取
        const cookieLanguage = this.getCookie(this.config.cookieName);
        if (this.isValidLanguage(cookieLanguage)) {
            this.currentLanguage = cookieLanguage;
            return;
        }
        
        // 3. 从浏览器语言获取
        const browserLanguage = navigator.language.split('-')[0];
        const matchedLanguage = this.config.supportedLanguages.find(
            lang => lang.startsWith(browserLanguage)
        );
        if (matchedLanguage) {
            this.currentLanguage = matchedLanguage;
            return;
        }
        
        // 4. 默认语言
        this.currentLanguage = this.config.defaultLanguage;
    }
    
    /**
     * 验证语言是否有效
     * @param {string} language 语言代码
     * @returns {boolean} 是否有效
     */
    isValidLanguage(language) {
        return language && this.config.supportedLanguages.includes(language);
    }
    
    /**
     * 加载语言文件
     * @param {string} language 语言代码
     */
    loadLanguage(language, retryCount = 0) {
        if (this.isLoading || this.currentLanguage === language) return;
        
        const maxRetries = 2;
        console.log(`[I18nManager] Loading language: ${language} (attempt ${retryCount + 1})`);
        this.isLoading = true;
        this.showLoadingIndicator();
        
        fetch(`${this.config.localePath}${language}.json`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Language file not found: ${language}`);
                }
                return response.json();
            })
            .then(translations => {
                console.log(`[I18nManager] Successfully loaded translations for ${language}:`, translations);
                this.translations = translations;
                console.log(`[I18nManager] Applying translations for ${language}`);
                this.applyTranslations();
                this.currentLanguage = language;
                this.savePreferredLanguage(language);
            })
            .catch(error => {
                console.error(`[I18nManager] Language load error (attempt ${retryCount + 1}):`, error);
                if (retryCount < maxRetries) {
                    const delay = Math.pow(2, retryCount) * 1000; // Exponential backoff
                    console.log(`[I18nManager] Retrying in ${delay}ms...`);
                    setTimeout(() => this.loadLanguage(language, retryCount + 1), delay);
                    return;
                }
                this.showErrorIndicator();
                // Fallback to default language if all retries fail
                if (language !== this.config.defaultLanguage) {
                    console.log(`[I18nManager] Falling back to default language: ${this.config.defaultLanguage}`);
                    this.loadLanguage(this.config.defaultLanguage);
                }
            })
            .finally(() => {
                if (retryCount === 0) { // Only run finally on initial call
                    this.isLoading = false;
                    this.hideLoadingIndicator();
                    this.updateLanguageButtons();
                }
            });
    }
    
    /**
     * 应用翻译到页面
     */
    applyTranslations() {
        if (!this.translations || Object.keys(this.translations).length === 0) return;
        
        // 动态获取所有带data-i18n属性的元素
        const elements = document.querySelectorAll('[data-i18n]');
        elements.forEach(element => {
            const key = element.getAttribute('data-i18n');
            const translation = this.getTranslation(key);
            if (translation !== null) {
                console.log(`[I18nManager] Translated '${key}' to '${translation}'`);
                element.textContent = translation;
            } else {
                console.warn(`[I18nManager] Missing translation for key: '${key}'`);
            }
        });
    }
    
    /**
     * 获取翻译文本
     * @param {string} key 翻译键
     * @returns {string|null} 翻译文本或null
     */
    getTranslation(key) {
        if (!key) return null;
        
        try {
            // 支持嵌套键如 "navigation.home"
            return key.split('.').reduce((obj, prop) => obj && obj[prop], this.translations);
        } catch (error) {
            console.error('Translation error:', error);
            return null;
        }
    }
    
    /**
     * 保存首选语言
     * @param {string} language 语言代码
     */
    savePreferredLanguage(language) {
        // 保存到本地存储
        localStorage.setItem(this.config.cookieName, language);
        
        // 保存到Cookie
        this.setCookie(this.config.cookieName, language, this.config.cookieExpires);
    }
    
    /**
     * 更新语言切换按钮状态
     */
    updateLanguageButtons() {
        this.languageButtons.forEach(button => {
            button.classList.toggle('active', button.dataset.language === this.currentLanguage);
        });
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        this.languageButtons.forEach(button => {
            button.addEventListener('click', () => {
                const language = button.dataset.language;
                if (this.isValidLanguage(language)) {
                    this.loadLanguage(language);
                }
            });
        });
        
        // 监听语言相关的路由变化(如果有)
        window.addEventListener('popstate', () => this.checkLanguageFromURL());
        
        // 监听语言切换事件
        window.addEventListener('languageChanged', (event) => {
            const newLang = event.detail.language;
            if (this.currentLanguage === newLang) {
                this.applyTranslations();
            } else {
                this.loadLanguage(newLang);
            }
        });
    }
    
    /**
     * 从URL检查语言(如果有语言参数)
     */
    checkLanguageFromURL() {
        const urlParams = new URLSearchParams(window.location.search);
        const language = urlParams.get('lang');
        if (this.isValidLanguage(language)) {
            this.loadLanguage(language);
        }
    }
    
    /**
     * 设置Cookie
     * @param {string} name Cookie名称
     * @param {string} value Cookie值
     * @param {number} days 过期天数
     */
    setCookie(name, value, days) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        const expires = `expires=${date.toUTCString()}`;
        document.cookie = `${name}=${value}; ${expires}; path=/; SameSite=Lax`;
    }
    
    /**
     * 获取Cookie
     * @param {string} name Cookie名称
     * @returns {string|null} Cookie值
     */
    getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
        return null;
    }
    
    /**
     * 显示加载指示器
     */
    showLoadingIndicator() {
        // 创建加载指示器
        const loadingIndicator = document.createElement('div');
        loadingIndicator.id = 'i18n-loading';
        loadingIndicator.className = 'loading-indicator';
        loadingIndicator.innerHTML = '<div class="spinner"></div><span>加载语言...</span>';
        
        // 添加到页面
        document.body.appendChild(loadingIndicator);
    }
    
    /**
     * 隐藏加载指示器
     */
    hideLoadingIndicator() {
        const loadingIndicator = document.getElementById('i18n-loading');
        if (loadingIndicator) {
            // 添加淡出动画
            loadingIndicator.style.opacity = '0';
            loadingIndicator.style.transition = 'opacity 0.3s ease';
            
            // 动画结束后移除
            setTimeout(() => {
                loadingIndicator.remove();
            }, 300);
        }
    }
    
    /**
     * 显示错误指示器
     */
    showErrorIndicator() {
        const errorIndicator = document.createElement('div');
        errorIndicator.id = 'i18n-error';
        errorIndicator.className = 'error-indicator';
        errorIndicator.innerHTML = '<span>语言加载失败，已使用默认语言</span>';
        
        // 添加到页面
        document.body.appendChild(errorIndicator);
        
        // 3秒后自动移除
        setTimeout(() => {
            errorIndicator.remove();
        }, 3000);
    }
}

// 初始化国际化模块
document.addEventListener('DOMContentLoaded', function() {
    const i18n = new I18nManager();
    i18n.init();
});